<template>
	<view style="padding-bottom: 130rpx;">
		<view class="formContainer">
			<uni-forms ref="form">
				<uni-forms-item label="还车日期" required>
					<view style="color: #333;font-size: 28rpx;">
						<uni-datetime-picker type="datetime" v-model="returnTime" :start="rentalEndTime"
							@change="timeChange" />
						<text v-if="costInfo"
							style="font-size: 26rpx;color: #ff3336;flex-grow: 1;">续租{{ costInfo.days }}天
						</text>
					</view>
				</uni-forms-item>
				<uni-forms-item v-if="electronicContractEnable==1" label="签署续租合同" label-width="90">
					<view>
						<u-switch v-model="contractStatus" :activeValue="2" :inactiveValue="1"
							:disabled="verificationContractInfo.status==2"></u-switch>
						<text style="color: red;margin-top: 10rpx">{{ verificationContractInfo.operationPrompt }}</text>
					</view>
				</uni-forms-item>
				<uni-forms-item label="费用总计" required>
					<view>
						<u--input v-model="totalRent" placeholder="自动计算不可修改" disabled></u--input>
					</view>
				</uni-forms-item>


				<block v-if="tableData.length > 0">
					<view v-for="(item, index) in tableData" :key="index" style="margin: 20rpx 0">
						<!-- 费用项标题及操作按钮 -->
						<view class="flex-row-center-sb" style="margin-bottom: 20rpx;">
							<text style="font-size: 28rpx;color: #666;">{{ item.chargeProjectName }}</text>

							<block v-if="item.isRent == 1">
								<text style="font-size: 26rpx;color: #2879FF;"
									@click.stop="showRentDetail = !showRentDetail">
									日租金明细
								</text>
							</block>
							<block v-else>
								<view class="flex-row" v-if="item.canEdit != 1">
									<u-switch v-if="item.isOptional == 1" v-model="item.selected" size="20"></u-switch>
									<template v-if="item.canEdit == 3">
										<!-- 编辑按钮 -->
										<view style="margin-right: 20rpx;margin-left: 20rpx;"
											@click="editCostItem(2, index, item)">
											<u-icon name="edit-pen" color="#2879FF" size="24"></u-icon>
										</view>
										<!-- 删除按钮 -->
										<view @click="deleteCostItem(index)">
											<u-icon name="trash" color="#2879FF" size="24"></u-icon>
										</view>
									</template>

								</view>
							</block>
						</view>

						<uni-table ref="table" :loading="loading" border stripe>
							<uni-tr>
								<uni-th width="100" align="center">
									<text style="color: #2879FF;">单价({{ item.chargeItemsType | chargeItemsType }})
									</text>
								</uni-th>
								<uni-th width="100" align="center">
									<text style="color: #2879FF;">数目</text>
								</uni-th>
								<uni-th width="100" align="center">
									<text style="color: #2879FF;">费用</text>
								</uni-th>
							</uni-tr>
							<uni-tr>
								<uni-td align="center">
									<u--input v-model="item.unitPrice" @input="check" type="digit"
										placeholder="请输入单价"></u--input>
								</uni-td>
								<!-- <uni-td align="center" v-if="item.canEdit == 2">
                   <uni-easyinput v-model="item.number" :clearable="false" type="number"
                     :placeholder="item.number">
                     {{item.number}}
                   </uni-easyinput>
                 </uni-td> -->
								<!-- <uni-td v-else align="center">{{ item.number }}</uni-td> -->
								<uni-td align="center">{{ item.number }}</uni-td>
								<uni-td align="center">{{ item.chargeMoney }}</uni-td>
							</uni-tr>
						</uni-table>
					</view>

					<view class="flex-xy-center">
						<view class="flex-row-center addCost" @click="editCostItem(1)">
							<u-icon name="plus-circle" color="#fff"></u-icon>
							<text style="color: #fff;font-size: 26rpx;margin-left: 20rpx;">添加收费项</text>
						</view>
					</view>
				</block>
			</uni-forms>
		</view>

		<!-- 新增收费项弹框 -->
		<u-popup :show="showEditCost" mode="bottom" @close="showEditCost = false" closeable round="12">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx 20rpx;">
				<view style="margin-bottom: 30rpx;">{{ popTitleType == 1 ? '新增' : '编辑' }}收费项</view>
				<uni-forms ref="form">
					<uni-forms-item label="收费项名称" labelWidth="90" required>
						<view>
							<u--input v-model="customCost.chargeProjectName" :disabled="customCost.canEdit != 3"
								placeholder="请输入收费项名称"></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="收费类型" required>
						<uni-data-checkbox v-model="customCost.chargeItemsType" :disabled="customCost.canEdit != 3"
							:localdata="chargeItemsTypes" />
					</uni-forms-item>

					<uni-forms-item label="单价" type="number" labelWidth="90" required>
						<view>
							<u--input v-model="customCost.unitPrice" @input="check" type="digit"
								placeholder="请输入单价"></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="数目" labelWidth="90" required>
						<view>
							<u--input v-model="customCost.number" type="number" placeholder="请输入数量"></u--input>
						</view>
					</uni-forms-item>

					<uni-forms-item label="费用合计" labelWidth="90">
						<view>
							<text
								style="position: relative;top: 15rpx;">{{ customCost.number * customCost.unitPrice || '0' }}
							</text>
						</view>
					</uni-forms-item>
				</uni-forms>

				<view class="commitBtn" @click="commitCost">提交</view>
			</view>
		</u-popup>

		<u-popup :show="showRentDetail" mode="center" @close="showRentDetail = false" closeable round="12">
			<view class="flex-colum-center" style="padding: 40rpx 24rpx">
				<view style="margin-bottom: 30rpx;">费用租赁明细</view>
				<scroll-view scroll-y="true">
					<view style="max-height: 800rpx;">
						<view class="flex-row-center-sb payCostItem" v-for="(item, index) in planPriceVoList"
							:key="index">
							<text>{{ item.time }}</text>
							<text>{{ item.price }}元</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<button type="info" :loading="loading" class="sub-btn" @click="confimRelet">确认续租</button>
	</view>
</template>

<script>
	import * as orderApi from '@/api/order-api.js';

	export default {
		data() {
			return {
				loading: false,
				verificationContractInfo: {},
				contractStatus: 1,
				rentalEndTime: null,
				orderNo: '',
				returnTime: this.parseTime(new Date()), //还车时间
				costInfo: null,
				dayliyRent: '',
				showEditCost: false,
				showRentDetail: false, //日租金明细
				tableData: [],
				currentEditCostIndex: -1,
				popTitleType: 1,
				customCost: {
					chargeProjectName: 0,
					chargeMoney: '',
					chargeItemsType: 1,
					canEdit: 3,
					number: '',
					unitPrice: '',
					isRent: 2,
					chargeProjectCategory: 9
				},
				planPriceVoList: [],
				chargeItemsTypes: [{
						value: 1,
						text: '按次'
					},
					{
						value: 2,
						text: '按天'
					},
					{
						value: 6,
						text: '按个'
					}
				]
			};
		},
		computed: {
			electronicContractEnable() {
				return this.$store.state.initData.initData.electronicContractEnable;
			},
			totalRent() {
				let total = 0;
				if (this.tableData.length > 0) {
					this.tableData.map(item => {
						item.selected = item.selected;
						//可编辑
						if (item.canEdit != 1) {
							if (item.chargeItemsType == 2) {
								//按天->开关,无上限限制
								item.chargeMoney = item.number * item.unitPrice;
								item.calculate = item.unitPrice + '×' + item.number;
								return item;
							} else {
								////按次|按个->步进器->有最大金额限制
								if (item.number > 0) {
									//当次数|个数大于0时
									const itemCost = item.number * item.unitPrice; //计算出来的金额
									if (item.upperLimitOfAmount != -1) {
										//金额有上限
										if (itemCost > item.upperLimitOfAmount) {
											//当金额大于最大限制金额->取最大金额
											item.chargeMoney = item.upperLimitOfAmount;
											item.calculate = item.unitPrice + '×️' + item.number;
											return item;
										} else {
											//当在最大金额范围内
											item.chargeMoney = item.number * item.unitPrice;
											item.calculate = item.unitPrice + '×' + item.number;
											return item;
										}
									} else {
										//金额无上限
										item.chargeMoney = item.number * item.unitPrice;
										item.calculate = item.unitPrice + '×' + item.number;
										return item;
									}
								} else {
									item.chargeMoney = item.number * item.unitPrice;
									item.calculate = item.unitPrice + '×' + item.number;
									return item;
								}
							}
						} else {
							item.chargeMoney = item.number * item.unitPrice;
							item.calculate = item.unitPrice + '×' + item.number;
							return item;
						}
					});
					this.tableData.map(item => {
						if (item.selected) {
							total += Number(item.chargeMoney);
						}
					});
				}

				return total.toFixed(2);
			}
		},
		onLoad(option) {
			const item = JSON.parse(decodeURIComponent(option.item));
			this.orderNo = item.orderNo;
			this.rentalEndTime = item.rentalEndTime;
			this.returnTime = this.parseTime(item.rentalEndTime);
			this.getVerificationContract();
		},
		methods: {
			/*获取续租合同签署验证信息*/
			getVerificationContract() {
				orderApi.verificationContract(this.orderNo).then((res) => {
					this.verificationContractInfo = res.data;
				})
			},
			check(e) {
				//正则表达试
				e = e.match(/^\d*(\.?\d{0,2})/g)[0] || null;
				this.$nextTick(() => {
					this.customCost.unitPrice = e;
				});
			},
			// 选择还车时间
			timeChange(e) {
				this.returnTime = this.parseTime(e);
				this.getRenewalFee();
			},

			// 查询费用信息
			getRenewalFee() {
				orderApi
					.renewalFee({
						orderNo: this.orderNo,
						takeAlsoTime: this.returnTime
					})
					.then(res => {
						this.costInfo = res.data;
						this.tableData = this.costInfo.chargingItemsVoList;
						this.tableData = this.tableData.map(item => {
							if (item.isOptional == 2) {
								item.selected = true;
							} else {
								item.selected = false;
							}
							return item;
						});
						this.dayliyRent = this.costInfo.rent / this.costInfo.days;
						this.planPriceVoList = this.costInfo.planPriceVoList;
					});
			},
			// 删除费用项
			deleteCostItem(index) {
				this.tableData.splice(index, 1);
			},

			// 添加或者编辑自定义费用项
			editCostItem(type, index, info) {
				this.popTitleType = type;
				if (type == 1) {
					//新增
					this.customCost = {
						chargeProjectName: '',
						chargeMoney: '',
						chargeItemsType: 1,
						canEdit: 3,
						number: '',
						unitPrice: '',
						isRent: 2,
						chargeProjectCategory: 9,
						selected: true,
						calculate: ''
					};
				} else {
					//编辑
					this.customCost = info;
					this.currentEditCostIndex = index;
				}
				this.showEditCost = true;
			},
			//确定提交费用项
			commitCost() {
				if (uni.$u.test.isEmpty(this.customCost.chargeProjectName)) {
					uni.$u.toast('请输入费用项名称');
					return;
				} else if (uni.$u.test.isEmpty(this.customCost.unitPrice)) {
					uni.$u.toast('请输入单价');
					return;
				} else if (uni.$u.test.isEmpty(this.customCost.number)) {
					uni.$u.toast('请输入数目');
					return;
				} else if (this.customCost.number == '0') {
					uni.$u.toast('数目不能为0,请重新输入');
					return;
				} else {
					if (this.popTitleType == 1) {
						//新增
						this.customCost.chargeMoney = Number(this.customCost.unitPrice) * Number(this.customCost.number);
						this.tableData.push(this.customCost);
						console.log(this.tableData);
					} else {
						//编辑
						this.tableData[this.currentEditCostIndex].chargeProjectName = this.customCost.chargeProjectName;
						this.tableData[this.currentEditCostIndex].unitPrice = this.customCost.unitPrice;
						this.tableData[this.currentEditCostIndex].number = this.customCost.number;
						this.tableData[this.currentEditCostIndex].chargeItemsType = this.customCost.chargeItemsType;
						this.tableData[this.currentEditCostIndex].canEdit = this.customCost.canEdit;
						this.tableData[this.currentEditCostIndex].chargeMoney =
							Number(this.customCost.unitPrice) * Number(this.customCost.number);
						this.tableData[this.currentEditCostIndex].calculate = this.customCost.unitPrice + '×️';
						this.customCost.number;
						this.tableData[this.currentEditCostIndex].isRent = this.customCost.isRent;
					}

					this.showEditCost = false;
				}
			},

			confimRelet() {
				if (uni.$u.test.isEmpty(this.returnTime)) {
					uni.$u.toast('请选择还车日期');
					return;
				} else if (this.costInfo == null) {
					uni.$u.toast('请修改还车日期');
					return;
				} else {
					let chargeItemsVo = this.tableData.filter(item => {
						return item.selected == true && item.chargeMoney != 0;
					});
					uni.showModal({
						title: '提示',
						content: '您确认续租吗?',
						cancelText: '取消',
						confirmText: '确认续租',
						success: res => {
							if (res.confirm) {
								this.loading = true
								uni.showLoading({
									title: '加载中...'
								})
								let params = {
									chargeItemsVo: chargeItemsVo,
									planPriceVoList: this.costInfo.planPriceVoList ?? null,
									leaseDays: this.costInfo.days,
									orderNo: this.orderNo,
									payType: 1,
									payWay: 1,
									rent: this.totalRent,
									rentalEndTime: this.parseTime(this.returnTime),
									contractStatus: this.contractStatus,
								}
								console.log('提交续租的数据', params);
								orderApi.decisionOrderRenewal(params)
									.then(res => {
										console.log('进来了-----------------');
										uni.$emit('refreshOrder');
										this.$u.toast('提交成功');
										uni.navigateBack({
											animationDuration: 300
										});

									}).finally(() => {
										uni.hideLoading();
										this.loading = false
									});
							}
						}
					});
				}
			},

			// 日期格式化
			parseTime(time, pattern) {
				if (arguments.length === 0 || !time) {
					return null;
				}
				const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
				let date;
				if (typeof time === 'object') {
					date = time;
				} else {
					if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
						time = parseInt(time);
					} else if (typeof time === 'string') {
						time = time
							.replace(new RegExp(/-/gm), '/')
							.replace('T', ' ')
							.replace(new RegExp(/\.[\d]{3}/gm), '');
					}
					if (typeof time === 'number' && time.toString().length === 10) {
						time = time * 1000;
					}
					date = new Date(time);
				}
				const formatObj = {
					y: date.getFullYear(),
					m: date.getMonth() + 1,
					d: date.getDate(),
					h: date.getHours(),
					i: date.getMinutes(),
					s: date.getSeconds(),
					a: date.getDay()
				};
				const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
					let value = formatObj[key];
					// Note: getDay() returns 0 on Sunday
					if (key === 'a') {
						return ['日', '一', '二', '三', '四', '五', '六'][value];
					}
					if (result.length > 0 && value < 10) {
						value = '0' + value;
					}
					return value || 0;
				});
				return time_str;
			}
		}
	};
</script>

<style lang="scss" scoped>
	.formContainer {
		margin: 40rpx 20rpx;
		padding: 24rpx;
		background-color: #fff;
		box-shadow: 0px 4rpx 16rpx 0px rgba(1, 10, 18, 0.1);
		border-radius: 16rpx;
	}

	.addCost {
		margin: 32rpx 0;
		box-sizing: border-box;
		padding-left: 30rpx;
		width: 242rpx;
		height: 60rpx;
		background: #1673ff;
		border-radius: 30rpx;
	}

	.payCostItem {
		height: 80rpx;
		width: 600rpx;
		border-bottom: 1rpx solid #ededed;
		font-size: 28rpx;
		color: #333;
	}

	.commitBtn {
		background-color: #1673ff;
		border-radius: 12rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		width: 300rpx;
		margin-top: 30rpx;
	}
</style>